// index.js
// 获取应用实例
const app = getApp()
import {
  formatTime
} from './../../utils/util'
const {
  Tool,
  API,
  Storage
} = global.$util

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: true,
    show: false,
    formatTime: formatTime(new Date()),
    encrypted: '',
    iv: '',
    sessionKey: '',
    openid: '',
    sex: '',
    userName: '',
    avatar: '',
    sex: '',
    showShop: false
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  // 授權彈窗
  onAlert() {
    const that = this
    wx.showModal({
      title: '温馨提示',
      content: '正在请求您的个人信息',
      success(res) {
        if (res.confirm) {
          wx.getUserProfile({
          desc: "获取你的昵称、头像、地区及性别",
          success: res => {
            console.log(res)
            let wxUserInfo = res.userInfo;
            that.setData({
              iv: res.iv,
              userName: wxUserInfo.nickName,
              sex: wxUserInfo.gender,
              avatar: wxUserInfo.avatarUrl,
              encrypted: res.encryptedData
            });
            API.getRegister({
              encrypted: that.data.encrypted,
              iv: that.data.iv,
              sessionKey: that.data.sessionKey,
              sex: that.data.sex,
              openid: that.data.openid,
              userName: that.data.userName,
              avatar: that.data.avatar
            }).then(res=>{
              console.log(res, 222222);
              that.setData({
                showShop: true
              })
              if (Storage.getShopId()) {
                Tool.switchTab('/pages/mine/mine')
              } else {
                that.getShopList()
              }
            }).catch(err=>{})
          },
          fail: res => {
             //拒绝授权
            wx.showErrorModal('您拒绝了请求');
            return;
          }
        })} else if (res.cancel) {
          //拒绝授权 showErrorModal是自定义的提示
          wx.showErrorModal('您拒绝了请求');
          return;
        }
      }
    })
  },

  onLoad() {
    const _this = this
   
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    wx.login({
      success: function (res) {
        if (res.code) {
          API.getOpenedId({code: res.code}).then(data => {
            Storage.setWxOpenid(data.data.data.openid)
            if (data.data.data.token) {
              Storage.setToken(data.data.data.token)
              if (Storage.getShopId()) {
                // 已授權
                Tool.switchTab('/pages/mine/mine')
              } else {
                _this.setData({
                  showShop: true
                })
  
                _this.getShopList()
              }
              
            } else {
              // 未授權
              _this.setData({
                show: false,
                openid: data.data.data.openid,
                sessionKey: data.data.data.session_key,
              });
              _this.onAlert()
            }
          }).catch(err =>{
          })
        }
      }
    })
  },
  getShopList() {
    API.getShopList({}).then((res) => {
      this.setData({
        shopList: res.data.rows || []
      })
    }).catch((res) => {
      console.error(res)
    })
  },
  selectShop(e) {
    let shopId = e.currentTarget.dataset.id
    API.setShopCache({
      shopId: shopId
    }).then(() => {
      this.setData({
        showShop: false
      })
      wx.showToast({
        title: '当前店铺已切换为：' + e.currentTarget.dataset.name,
        icon: 'none',
        duration: 1500,
        success: () => {
          Storage.setShopId(shopId)
          setTimeout(() => {
            Storage.setShopId(shopId)
            Tool.switchTab('/pages/mine/mine')
          }, 1500)
        }
      })
    }).catch(() =>{
      //
    })
  },
  toAddShop(){
    Tool.navigateTo('/pages/mine/shop/add-shop/add-shop')
  }
})